package com.leetcode;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * 20. 有效的括号
 * 栈
 *
 * @author fy
 * @date 2022/4/12 16:53
 */
public class Solution20_1 {

    private final static Map<Character, Character> PAIRS = new HashMap<Character, Character>(3) {
        {
            put(')', '(');
            put('}', '{');
            put(']', '[');
        }
    };

    public boolean isValid(String s) {
        if (s == null) {
            return false;
        }
        if (s.length() % 2 == 1) {
            return false;
        }
        Deque<Character> stack = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (PAIRS.containsKey(ch)) {
                if (stack.isEmpty() || !stack.peek().equals(PAIRS.get(ch))) {
                    return false;
                }
                stack.pop();
            } else {
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }
}
